package com.my.study.juc.basic.syn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/4/8 23:34
 **/
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket ticket = new BuyTicket();

        new Thread(ticket, "A").start();
        new Thread(ticket, "B").start();
        new Thread(ticket, "C").start();

    }


}

class BuyTicket implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(BuyTicket.class);

    /**
     * 票
     * <p>临界值</p>
     */
    private int ticketNums = 10;

    /**
     * 线程停止标识
     */
    private volatile boolean flag = true;

    @Override
    public void run() {
        // 买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                LOGGER.error("错误", e);
            }
        }
    }

    private void buy() throws InterruptedException {
        if (ticketNums <= 0) {
            flag = false;
            return;
        }

        // 模拟延时
        Thread.sleep(100);

        // 核心操作-买票
        System.out.println(Thread.currentThread().getName() + "拿到了第 " + ticketNums-- + " 张票");
    }
}
